import 'package:flutter/material.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/model/user_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/my/my_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:provider/provider.dart';

/// @description: 我的页面
/// @author tangzhentao
/// @created at 21:38 2024/11/25

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<StatefulWidget> createState() => _MyState();
}

class _MyState extends State<MyPage> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    context.read<UserProvider>().updateShopInfo();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    /// 是否有商铺
    final hasShop = context.read<UserProvider>().isShopOwner();
    final children = [
      _serviceItemWidget(Res.imagesMyInvoice, '我的发票', onTap: () => XfgNav.pushNamed(Routes.myInvoice)),
      _serviceItemWidget(Res.imagesMyFundDetails, '资金明细', onTap: () => XfgNav.pushNamed(Routes.myFundDetails)),
      _serviceItemWidget(Res.imagesMySettings, '设置', onTap: () => XfgNav.pushNamed(Routes.settings)),
      _serviceItemWidget(Res.imagesMyAddress, '收货地址', onTap: () => XfgNav.pushNamed(Routes.myAddress),
          radius: hasShop ? BorderRadius.only(bottomLeft: Radius.circular(XfgSize().size6)):null),
      _serviceItemWidget(Res.imagesMyIntegralOrder, '积分订单', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.points}),
          radius: hasShop ? null:BorderRadius.only(bottomLeft: Radius.circular(XfgSize().size6))),
      _serviceItemWidget(Res.imagesMyInvestOrder, '投资订单', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.gold})),
      _serviceItemWidget(Res.imagesMyReturnOrder, '回收订单', onTap: () => XfgNav.pushNamed(Routes.myOrderRecover),
          radius: hasShop ? BorderRadius.only(bottomLeft: Radius.circular(XfgSize().size6)):null)
    ];
    if (hasShop) {
      children.insert(1, _serviceItemWidget(Res.imagesMyShop, '我的店铺', onTap: () => XfgNav.pushNamed(Routes.myShop)));
    } else {
      children.add(Container(decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.only(bottomRight: Radius.circular(XfgSize().size6)))));
    }
    return ProviderWidget<MyViewmodel>(
      model: MyViewmodel(),
      builder: (ctx, home) => Stack(
        children: [
          Image.asset(Res.imagesHomeTop, width: XfgSize().screenWidth, height: XfgSize().size236),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
            child: CustomScrollView(
              slivers: [
                /// 用户信息
                SliverToBoxAdapter(
                  child: Container(
                    margin: EdgeInsets.only(top: XfgSize().size26 + XfgSize().statusBarHeight),
                    height: XfgSize().size70,
                    child: Builder(builder: (ctx) {
                      final user = ctx.select<UserProvider, UserModel>((k) => k.user);
                      return Row(
                        children: [
                          HttpImage(user.avatar, size: Size.square(XfgSize().size70), placeholder: Res.imagesAvatar, radius: BorderRadius.circular(XfgSize().size70)),
                          SizedBox(width: XfgSize().size18),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Row(
                                  children: [
                                    XfgText(user.nickname?? '梦想家', fontSize: XfgSize().text20, color: XfgColor.white, bold: FontWeight.w500),
                                    Container(
                                      margin: EdgeInsets.only(left: XfgSize().size3),
                                      height: XfgSize().size16,
                                      width: XfgSize().size14 + xfgBoundingTextSize('V0会员', style: TextStyle(fontSize: XfgSize().text10)).width,
                                      decoration: BoxDecoration(border: Border.all(color: XfgColor.white, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size16)),
                                      alignment: Alignment.center,
                                      child: XfgText('V0会员', fontSize: XfgSize().text10, color: XfgColor.white),
                                    )
                                  ],
                                ),
                                SizedBox(height: XfgSize().size12),
                                XfgText('UID:${user.uid?? ''}', fontSize: XfgSize().text16, color: XfgColor.white),
                              ],
                            ),
                          )
                        ],
                      );
                    }),
                  ),
                ),
                /// 资金
                SliverToBoxAdapter(
                  child: Builder(builder: (con) {
                    final user = con.select<UserProvider, UserModel>((k) => k.user);

                    return Container(
                      decoration: white6Decoration,
                      margin: EdgeInsets.only(top: XfgSize().size20),
                      child: Column(
                        children: [
                          Container(
                            height: XfgSize().size56 + XfgSize().size0_5,
                            decoration: bottomBorderDecoration,
                            padding: EdgeInsets.symmetric(horizontal: XfgSize().size18),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: XfgText('可提现  ', fontSize: XfgSize().text16, color: XfgColor.text2, textAlign: TextAlign.end, overflow: TextOverflow.ellipsis, children: [
                                    TextSpan(text: '¥', style: TextStyle(fontSize: XfgSize().text12)),
                                    TextSpan(text: user.amount?.toStringAsFixed(2)?? '0.00', style: TextStyle(fontSize: XfgSize().text24, color: XfgColor.theme, fontWeight: FontWeight.bold)),
                                  ]),
                                ),
                                GestureDetector(
                                  onTap: () => XfgNav.pushNamed(Routes.myWithdrawal),
                                  child: Container(
                                    width: XfgSize().size90,
                                    height: XfgSize().size34,
                                    decoration: BoxDecoration(gradient: XfgColor.withdrawalGradient, borderRadius: BorderRadius.circular(XfgSize().size16)),
                                    alignment: Alignment.center,
                                    child: XfgText('提现', fontSize: XfgSize().text18, color: XfgColor.theme),
                                  ),
                                )
                              ],
                            ),
                          ),
                          SizedBox(
                            height: XfgSize().size88,
                            child: Row(
                              children: [
                                _moneyItemWidget('余额', user.points?.toStringAsFixed(2)?? '0.00', unit: '¥'),
                                _moneyItemWidget('积分', user.points?.toStringAsFixed(1)?? '0.0', onTap: () => XfgNav.pushNamed(Routes.myIntegral)),
                                _moneyItemWidget(user.role == 2 ? '销量':'', user.role == 2 ? '1358':'')
                              ],
                            ),
                          )
                        ],
                      ),
                    );
                  }),
                ),
                /// 我的订单
                SliverToBoxAdapter(
                  child: Container(
                    decoration: white6Decoration,
                    margin: EdgeInsets.symmetric(vertical: XfgSize().size10),
                    child: Column(
                      children: [
                        GestureDetector(
                          onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.product}),
                          child: Container(
                            height: XfgSize().size56 + XfgSize().size0_5,
                            decoration: bottomBorderDecoration,
                            padding: EdgeInsets.symmetric(horizontal: XfgSize().size15),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                XfgText('我的订单', fontSize: XfgSize().text20, color: XfgColor.text1, bold: FontWeight.bold),
                                const Spacer(),
                                XfgText('全部   ', fontSize: XfgSize().text14, color: XfgColor.text3),
                                Image.asset(Res.imagesArrowRight, width: XfgSize().size10, height: XfgSize().size15)
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: XfgSize().size88,
                          child: Row(
                            children: [
                              _orderItemWidget(Res.imagesMyToPay, '待付款', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.product, 'orderStatus': OrderStatus.paying})),
                              _orderItemWidget(Res.imagesMyWaitingReceipt, '待收货', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.product, 'orderStatus': OrderStatus.receiving})),
                              _orderItemWidget(Res.imagesMyDone, '已完成', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.product, 'orderStatus': OrderStatus.done})),
                              _orderItemWidget(Res.imagesMyReturnGoods, '退货', onTap: () => XfgNav.pushNamed(Routes.myOrder, arguments: {'orderType': ProductType.product, 'orderStatus': OrderStatus.cancel}))
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                /// 邀请
                SliverToBoxAdapter(
                  child: GestureDetector(
                    onTap: () => XfgNav.pushNamed(Routes.myInvite),
                    child: Image.asset(Res.imagesMyInvite, width: XfgSize().screenWidth, height: XfgSize().size62),
                  ),
                ),
                /// 我的服务
                SliverToBoxAdapter(
                  child: Container(
                    height: XfgSize().size56 + XfgSize().size0_5,
                    margin: EdgeInsets.only(top: XfgSize().size10),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.vertical(top: Radius.circular(XfgSize().size6)),
                        border: Border(bottom: BorderSide(color: XfgColor.colorE, width: XfgSize().size0_5))
                    ),
                    padding: EdgeInsets.only(left: XfgSize().size15),
                    alignment: Alignment.centerLeft,
                    child: XfgText('我的服务', fontSize: XfgSize().text20, color: XfgColor.text1, bold: FontWeight.bold),
                  ),
                ),
                SliverGrid(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4, childAspectRatio: 1.04),
                  delegate: SliverChildListDelegate(children),
                ),
                SliverToBoxAdapter(child: SizedBox(height: XfgSize().size10))
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 资金ItemWidget
  Widget _moneyItemWidget(String text, String value, {String unit = '', GestureTapCallback? onTap}) => Expanded(
    child: GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          XfgText(unit, fontSize: XfgSize().text12, color: XfgColor.text1, maxLines: 1, overflow: TextOverflow.ellipsis, children: [
            TextSpan(text: value, style: TextStyle(fontSize: XfgSize().text24, fontWeight: FontWeight.bold))
          ]),
          SizedBox(height: XfgSize().size15),
          XfgText(text, fontSize: XfgSize().text14, color: XfgColor.text2),
          SizedBox(height: XfgSize().size18)
        ],
      ),
    ),
  );

  /// 订单ItemWidget
  Widget _orderItemWidget(String image, String text, {GestureTapCallback? onTap}) => Expanded(
    child: GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          Image.asset(image, width: XfgSize().size28, height: XfgSize().size28),
          SizedBox(height: XfgSize().size10),
          XfgText(text, fontSize: XfgSize().text14, color: XfgColor.text2),
        ],
      ),
    ),
  );

  /// 服务ItemWidget
  Widget _serviceItemWidget(String image, String text, {BorderRadius? radius, GestureTapCallback? onTap}) => InkWell(
    onTap: onTap,
    child: Container(
      decoration: BoxDecoration(color: XfgColor.white, borderRadius: radius),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          Image.asset(image, width: XfgSize().size28, height: XfgSize().size22),
          SizedBox(height: XfgSize().size8),
          XfgText(text, fontSize: XfgSize().text14, color: XfgColor.text2),
        ],
      ),
    ),
  );

  @override
  bool get wantKeepAlive => true;
}
